/*
 * @Author: ygl
 * @Date: 2021-12-13 15:53:47
 * @LastEditors: ygl
 * @LastEditTime: 2021-12-14 09:58:01
 * @Description: JavaScript时间处理工具类
 */

/**
 * 判断时候是1-9，是的话就在前面添加0，变成01-09
 * @param n 字符串
 */
export const formatNumber = function (n) {
  n = n.toString();
  return n[1] ? n : `0${n}`;
};

/**
 * 按照用户需要格式化时间日期
 * @param {Data} time 标准时间
 * @param {String} pattern 格式化规则
 */
export function formatTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = pattern || "yyyy-MM-dd hh:mm:ss";
  let date;
  if (typeof time === "object") {
    date = time;
  } else {
    if (typeof time === "string" && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    } else if (typeof time === "string") {
      time = time
        .replace(new RegExp(/-/gm), "/")
        .replace("T", " ")
        .replace(new RegExp(/\.[\d]{3}/gm), "");
    }
    if (typeof time === "number" && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    M: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    m: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
    q: Math.floor((date.getMonth() + 3) / 3), // 季度
    S: date.getMilliseconds(), // 毫秒
  };
  const time_str = format.replace(/([yMdhmsqS])+/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === "a") {
      return ["日", "一", "二", "三", "四", "五", "六"][value];
    }
    if (result.length > 0 && value < 10) {
      value = "0" + value;
    }
    return value || 0;
  });
  return time_str;
}

/**
 * 获取一个月的最后一天
 * @param {标准时间} times
 */
export const getCurrentMonthLast = function (times) {
  const now = new Date(times);
  const year = now.getFullYear();
  const month = now.getMonth() + 1;
  const endOfMonth = new Date(year, month, 0).getDate();
  return `${now.getFullYear()}-${formatNumber(month)}-${endOfMonth}`;
};

/**
 *  获取当月的天数
 */
export const mGetDate = function () {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  // 获取本月的第0天就是上月的最后一天
  const days = new Date(year, month, 0);
  return days.getDate();
};
/**
 * 获取本周所有日期
 */
export const getWeekDay = function () {
  const date = new Date();
  const Monday = formatMonth(date.setDate(date.getDate() - date.getDay() + 1));
  const Tuesday = formatMonth(date.setDate(date.getDate() - date.getDay() + 2));
  const Wednesday = formatMonth(
    date.setDate(date.getDate() - date.getDay() + 3)
  );
  const Thursday = formatMonth(
    date.setDate(date.getDate() - date.getDay() + 4)
  );
  const Friday = formatMonth(date.setDate(date.getDate() - date.getDay() + 5));
  const Saturday = formatMonth(
    date.setDate(date.getDate() - date.getDay() + 6)
  );
  const Sunday = formatMonth(date.setDate(date.getDate() - date.getDay() + 7));
  const weekDay = [
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday,
  ];
  return weekDay;
};
/**
 * 获取当月所有日期
 */
export const getNowM = function () {
  const now = new Date();
  const currentMonthNum = mGetDate();
  const currentMonth = [];
  for (let i = 1; i <= currentMonthNum; i++) {
    const day = now.setDate(i);
    const everyDay = formatMonth(day);
    currentMonth.push(everyDay);
  }
  return currentMonth;
};

/**
 * 计算时间差
 * @param {Data} startTime 开始时间
 * @param {Data} endTime   结束时间
 * return xx年xx天  || xx天xx小时 || xx小时xx分
 */
export const getDateDiff = function (startTime, endTime) {
  const sTime = new Date(startTime); // 开始时间
  const eTime = new Date(endTime); // 结束时间
  const timeOff = eTime - sTime; // 相差时间戳（毫秒数）
  const timeMinute = 1000 * 60;
  const timeHour = 1000 * 3600;
  const timeDay = 1000 * 3600 * 24;
  const timeYear = 1000 * 3600 * 24 * 365;
  if (timeOff / timeYear >= 1) {
    return `${parseInt(timeOff / timeYear, 10)}年${parseInt(
      (timeOff % timeYear) / timeDay,
      10
    )}天`;
  }
  if (timeOff / timeDay >= 1) {
    return `${parseInt(timeOff / timeDay, 10)}天${parseInt(
      (timeOff % timeDay) / timeHour,
      10
    )}小时`;
  }
  return `${parseInt(timeOff / timeHour, 10)}小时${parseInt(
    (timeOff % timeHour) / timeMinute,
    10
  )}分`;
};

/**
 * 秒数转为时分秒的形式
 * @param {秒数} seconds
 */
export const secondsFormat = function (seconds) {
  let ut = "早";
  if (seconds < 0) {
    ut = "晚";
    seconds = -seconds;
  }
  const day = Math.floor(seconds / (24 * 3600)); // Math.floor()向下取整
  const hour = Math.floor((seconds - day * 24 * 3600) / 3600);
  const minute = Math.floor((seconds - day * 24 * 3600 - hour * 3600) / 60);
  const second = seconds - day * 24 * 3600 - hour * 3600 - minute * 60;
  return `${ut + day}天${hour}时${minute}分${second}秒`;
};
